const axios = require('axios')

module.exports = {
   async sendRequest(sqlStr, payload){
    console.error(sqlStr)
    try {   
        let res = await axios.post(`http://${payload.ip}:${payload.port}/rest/sql`, sqlStr, {
            auth: {
            username: payload.user,
            password: payload.password
            },
            timeout: payload.timeout
        })
		let version = res.data.status?'2.x':'3.x'
		if(res.data.code==0){
			res.data.status = 'succ'
			res.data.head = res.data.column_meta.map(item => item[0])
			if (
			  /show /i.test(sqlStr) &&
			  /.stables/i.test(sqlStr) &&
			  res.data.head.length === 1 &&
			  res.data.head[0] === 'stable_name'
			) {
			  res.data.head[0] = 'name'
			}
		}
		if (res.data.status == 'succ'){
		    let head = res.data.head
		    let resData = res.data.data.map(item => Object.fromEntries(head.map((a, b) => [a, item[b]])))
		    return {'res': true,'version':version, 'count': res.data.rows, 'data': resData}
		}else{
		    return {'res':false,'msg':res.data.desc,'code':res.data.code}
		}
    } catch (err) {
        if (err.response){
            return {'res':false,'msg':err.response.data.desc,'code':err.response.data.code}
        }else{
            return {'res':false,'msg':'连接错误','code':-1}
        }
    }
   },
   showDatabases(payload){
        return this.sendRequest('SHOW DATABASES', payload)
   },
   testConnect(payload){
        return this.sendRequest('SELECT SERVER_VERSION()', payload).then(a =>
            {
                if (a.res === false && a.code === -1){
                    return false
                }else{
                    return true
                }
            }
        )
   },
   getVersion(payload){
        //获取服务器版本    
        return this.sendRequest('SELECT SERVER_VERSION()', payload).then(a =>
            {
                if (a.res === false){
                    return 'unkown'
                }else{
                    return a.data[0]['server_version()']
                }
            }
        )
    },
   //添加数据库
   createDatabase(dbForm, payload){
	   let sqlStr = `CREATE DATABASE IF NOT EXISTS ${dbForm.name} comp ${dbForm.comp} replica ${dbForm.replica}`
	   sqlStr = sqlStr + ` keep ${dbForm.keep} update ${dbForm.update} quorum ${dbForm.quorum} blocks ${dbForm.blocks}`
	   sqlStr = sqlStr + ` cachelast ${dbForm.cachelast} wal ${dbForm.wal} fsync ${dbForm.fsync}`
       return this.sendRequest(sqlStr, payload)
   },
   alterDatabase(dbName,params,payload){
	   return this.sendRequest(`ALTER DATABASE ${dbName} ${params}`, payload)
   },
   dropDatabase(dbName, payload){
    return this.sendRequest(`DROP DATABASE IF EXISTS ${dbName}`, payload)
   },
   
   // 显示超表
   showSuperTables(dbName, payload,like=null){
    let likeStr = like?` LIKE '%${like}%'`:''
    return this.sendRequest(`SHOW ${dbName}.STABLES  ${likeStr}`, payload)
   },
   dropSTable(dbName,tableName, payload,safe=false){
    return this.sendRequest(`DROP STABLE  ${safe?'IF EXISTS':''} ${dbName}.${tableName}`, payload )
   },
   createStable(dbName,tableName,columns,tags, payload){
   	 return this.sendRequest(`CREATE STABLE IF NOT EXISTS ${dbName}.${tableName} (${columns}) TAGS (${tags})`, payload )  
   },
   describeStable(dbName,tableName,payload){
	  return this.sendRequest(`DESCRIBE  ${dbName}.${tableName}`, payload )   
   },
   /**
   	* 超表-添加列/标签
   	*/
   addStableColumnOrTag(dbName,tableName,columnStr,type,payload){
	   if(type==='column'){
			return this.sendRequest(`ALTER STABLE ${dbName}.${tableName} ADD COLUMN ${columnStr}`, payload )
	   }else{
			return this.sendRequest(`ALTER STABLE ${dbName}.${tableName} ADD TAG ${columnStr}`, payload )
	   }
   },
   /**
   	* 超表-修改列/标签
   	*/
   modifyStableColumnOrTag(dbName,tableName,columnStr,type,payload){
	   if(type==='column'){
	   		return this.sendRequest(`ALTER STABLE ${dbName}.${tableName} MODIFY COLUMN ${columnStr}`, payload )
	   }else{
	   		return this.sendRequest(`ALTER STABLE ${dbName}.${tableName} MODIFY TAG ${columnStr}`, payload )
	   }
   },
   /**
   	* 超表-修改标签名
   	*/
   modifyStableTagName(dbName,tableName,olderTag,tagStr,payload){
   	   	return this.sendRequest(`ALTER STABLE ${dbName}.${tableName} CHANGE TAG ${olderTag} ${tagStr}`, payload )
   },
   /**
	* 超表-删除列/标签
	*/
   dropStableColumnOrTag(dbName,tableName,column,type,payload){
	   if(type==='column'){
	   		return this.sendRequest(`ALTER STABLE ${dbName}.${tableName} DROP COLUMN ${column}`, payload )
	   }else{
	   		return this.sendRequest(`ALTER STABLE ${dbName}.${tableName} DROP TAG ${column}`, payload )
	   }
   },
   //分页查询超表
   selectStableData(dbName,tableName,page,limit,payload){
	   let start = (page-1)*limit
	   return this.sendRequest(`select count(*) as num from ${dbName}.${tableName}`,payload).then(countRes=>{
		   if(countRes.res){
			   if(countRes.data.length>0 && countRes.data[0].num>500000){
				   return this.sendRequest(`select * from ${dbName}.${tableName} limit ${start},${limit}`, payload).then(res=>{
					   if(countRes.data.length>0){
						   res.count=countRes.data[0].num
						   res.orderBy = 'asc'
					   }
					   return new Promise((resolve, reject)=>{resolve(res)})
				   })
			   }else{
				   return this.sendRequest(`select * from ${dbName}.${tableName} order by ts desc limit ${start},${limit}`, payload).then(res=>{
					   res.count=countRes.data[0].num
					   res.orderBy = 'desc'
					   return new Promise((resolve, reject)=>{resolve(res)})
				   })
			   }
		   }else{
			 return {'res':false,'msg':countRes.msg,'code':countRes.code}  
		   }
	   })
   },
   //基于超表创建子表
   createTableByStable(dbName,stableName,tableName,tagstr,payload){
	   return this.sendRequest(`CREATE TABLE IF NOT EXISTS ${dbName}.${tableName} USING ${dbName}.${stableName} ${tagstr}`, payload)
   },
   // 显示表
   showTables(dbName,stbName, payload,like=null){
		// return this.sendRequest(`SHOW ${dbName}.TABLES  ${likeStr}`, payload)
		if(stbName){
			let likeStr = like?`where tbname LIKE '%${like}%'`:''
			return this.sendRequest(`select DISTINCT tbname from ${dbName}.${stbName}  ${likeStr}`, payload)
		}else{
			let likeStr = like?`LIKE '%${like}%'`:''
			return this.sendRequest(`SHOW ${dbName}.TABLES  ${likeStr}`, payload)
		}
   },
   dropTable(dbName,tableName, payload,safe=false){
		return this.sendRequest(`DROP TABLE ${safe?'IF EXISTS':''} ${dbName}.${tableName}`, payload )
   },
   createTable(dbName,tableName,columns,payload){
		return this.sendRequest(`CREATE TABLE IF NOT EXISTS ${dbName}.${tableName} (${columns})`, payload )  
   },
   describeTable(dbName,tableName,payload){
		return this.sendRequest(`DESCRIBE ${dbName}.${tableName}`, payload )
   },
   /**
   	* 表-添加列
   	*/
   addTableColumn(dbName,tableName,columnStr,payload){
   	   return this.sendRequest(`ALTER TABLE ${dbName}.${tableName} ADD COLUMN ${columnStr}`, payload )
   },
   /**
   	* 表-修改列
   	*/
   modifyTableColumn(dbName,tableName,columnStr,payload){
   	   return this.sendRequest(`ALTER TABLE ${dbName}.${tableName} MODIFY COLUMN ${columnStr}`, payload )
   },
   /**
   	* 表-删除列
   	*/
   dropTableColumn(dbName,tableName,column,payload){
   	   return this.sendRequest(`ALTER TABLE ${dbName}.${tableName} DROP COLUMN ${column}`, payload )
   },
   
   //分页查询表
   selectTableData(dbName,tableName,page,limit,payload){
   	   let start = (page-1)*limit
   	   return this.sendRequest(`select count(*) as num from ${dbName}.${tableName}`,payload).then(countRes=>{
   		   if(countRes.res){
				if(countRes.data.length>0 && countRes.data[0].num>500000){
					return this.sendRequest(`select * from ${dbName}.${tableName} limit ${start},${limit}`, payload).then(res=>{
					   res.count=countRes.data[0].num
					   res.orderBy = 'asc'
					   return new Promise((resolve, reject)=>{resolve(res)})
					})
				}else{
					return this.sendRequest(`select * from ${dbName}.${tableName} order by _c0 desc limit ${start},${limit}`, payload).then(res=>{
					   if(countRes.data.length>0){
						   res.count=countRes.data[0].num
						   res.orderBy = 'desc'
					   }
					   return new Promise((resolve, reject)=>{resolve(res)})
					})
				}
   		   }else{
   			 return {'res':false,'msg':countRes.msg,'code':countRes.code}  
   		   }
   	   })
   },
   
   //终端查询
   rawSqlWithDB(dbName,sqlStr,payload){
        return this.sendRequest(sqlStr,payload)
    }
}

